package com.ruoyi.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HfuPayUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.constants.DyRoleKeyConstants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.DyAnchorPhotoBo;
import com.ruoyi.system.domain.bo.DyClientAnchorBo;
import com.ruoyi.system.domain.bo.DyOrderGoodsBo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IDyGoodsService;
import com.ruoyi.system.service.SysLoginService;
import com.ruoyi.system.vo.DyClientLoginVo;
import com.ruoyi.system.vo.HfuOrderResultVo;
import com.ruoyi.system.vo.HfuPayResultJsonWxVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyClientBo;
import com.ruoyi.system.domain.vo.DyClientVo;
import com.ruoyi.system.service.IDyClientService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 微信用户Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-02
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DyClientServiceImpl implements IDyClientService {

    private final DyClientMapper baseMapper;
    private final DyGoodsMapper dyGoodsMapper;
    private final DyAnchorMapper dyAnchorMapper;
    private final DyAnchorPhotoMapper dyAnchorPhotoMapper;
    private final DyOrderMapper dyOrderMapper;

    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private DyOrderServiceImpl dyOrderService;


    /**
     * 查询微信用户
     */
    @Override
    public DyClientVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询微信用户列表
     */
    @Override
    public TableDataInfo<DyClientVo> queryPageList(DyClientBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DyClient> lqw = buildQueryWrapper(bo);
        Page<DyClientVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询微信用户列表
     */
    @Override
    public List<DyClientVo> queryList(DyClientBo bo) {
        LambdaQueryWrapper<DyClient> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyClient> buildQueryWrapper(DyClientBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyClient> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), DyClient::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), DyClient::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), DyClient::getOpenId, bo.getOpenId());
        lqw.eq(StringUtils.isNotBlank(bo.getImgUrl()), DyClient::getImgUrl, bo.getImgUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getDes()), DyClient::getDes, bo.getDes());
        return lqw;
    }

    /**
     * 新增微信用户
     */
    @Override
    public Boolean insertByBo(DyClientBo bo) {
        DyClient add = BeanUtil.toBean(bo, DyClient.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改微信用户
     */
    @Override
    public Boolean updateByBo(DyClientBo bo) {
        DyClient update = BeanUtil.toBean(bo, DyClient.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DyClient entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除微信用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public DyClient createClient(String openId) {

        DyClient client = baseMapper.selectOne(new QueryWrapper<DyClient>().lambda().eq(DyClient::getOpenId, openId));
        if (client == null){
            DyClient c = new DyClient();
            c.setOpenId(openId);
            c.setCreateBy("admin");
            c.setCreateTime(new Date());
            c.setUpdateBy("admin");
            c.setUpdateTime(new Date());
            baseMapper.insert(c);
        }
        return client;
    }

    @Override
    public DyClient getUserInfoByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<DyClient>().lambda().eq(DyClient::getOpenId, openId));
    }

    @Override
    public R<DyClientLoginVo> login(DyClientBo bo) {

        if (StringUtils.isEmpty(bo.getUserName()) || StringUtils.isEmpty(bo.getPwd())){
            throw new ServiceException("帐号或密码不能为空");
        }

        DyClient client = baseMapper.selectOne(new LambdaQueryWrapper<DyClient>().eq(DyClient::getUserName, bo.getUserName()));
        if (client == null){
            throw new ServiceException("用户名或密码错误");
        }

        String token = sysLoginService.h5Login(bo.getPwd(), client);

        if (StringUtils.isEmpty(token)){
            throw new ServiceException("登录失败");
        }

        DyClientLoginVo vo = new DyClientLoginVo();
        vo.setToken(token);
        vo.setUserId(client.getId());

        return R.ok(vo);
    }

    @Override
    public R<DyClientLoginVo> register(DyClientBo bo) {

        if (StringUtils.isEmpty(bo.getUserName()) || StringUtils.isEmpty(bo.getPwd())){
            throw new ServiceException("帐号或密码不能为空");
        }

        DyClient client = baseMapper.selectOne(new LambdaQueryWrapper<DyClient>().eq(DyClient::getUserName, bo.getUserName()));
        if (client != null){
            throw new ServiceException("用户名已经存在，请更换后重试");
        }

        DyClient newClient = new DyClient();
        newClient.setOpenId("");
        newClient.setRealName("");
        newClient.setPwd(BCrypt.hashpw(bo.getPwd()));
        newClient.setUserName(bo.getUserName());
        newClient.setPhone("");
        newClient.setCreateBy("admin");
        newClient.setUpdateBy("admin");

        int i = baseMapper.insert(newClient);
        if (i == 0){
            throw new ServiceException("注册失败");
        }

        return R.ok();
    }

    /**
     * 下单主播
     * @param bo
     * @return
     */
    @Override
    public R<String> buyClientAnchor(DyClientAnchorBo bo) {

        if (bo == null || bo.getGoodsId() == null || bo.getClientId() == null || bo.getPayType() == null){
            throw new ServiceException("参数不全");
        }

        DyGoods goods = dyGoodsMapper.selectById(bo.getGoodsId());
        if (goods == null){
            throw new ServiceException("商品不存在");
        }

        DyClient client = baseMapper.selectById(bo.getClientId());
        if (client == null){
            throw new ServiceException("用户不存在");
        }

        DyOrderGoodsBo b = new DyOrderGoodsBo();
        b.setGoodsId(goods.getId());
        b.setPayType(bo.getPayType());

        return R.ok("ok", dyOrderService.addOrderPay(b));
    }


    /**
     * 下单主播相册
     * @param bo
     * @return
     */
    @Override
    public String buyClientAnchorPhoto(DyAnchorPhotoBo bo) {

        if (bo == null || bo.getClientId() == null || bo.getGoodsId() == null || bo.getPayType() == null){
            throw new ServiceException("参数不全");
        }

        //订单类型为相册， goodsId = anchorPhotoId
        DyAnchorPhoto photo = dyAnchorPhotoMapper.selectById(bo.getGoodsId());
        if (photo == null){
            throw new ServiceException("相册不存在");
        }

        DyClient client = baseMapper.selectById(bo.getClientId());
        if (client == null){
            throw new ServiceException("用户不存在");
        }

        DyGoods goods = dyGoodsMapper.selectOne(new LambdaQueryWrapper<DyGoods>().eq(DyGoods::getAnchorId, photo.getAnchorId()));

        //生成订单
        DyOrder order = new DyOrder();
        order.setOrderNo(dyOrderService.buildOrderNo());
        order.setOrderType(1);
        order.setAmount(photo.getPhotoMoney().intValue());
        order.setOrderStatus(0);
        order.setType(bo.getPayType());

        order.setAnchorId(photo.getAnchorId());
        order.setGoodsId(photo.getId());
        order.setGoodsName(goods.getName());
        order.setOpenId(bo.getOpenId());
//        order.setTradeNo();
//        order.setToken();

        order.setCreateTime(new Date());
        order.setCreateBy("admin");
        order.setUpdateTime(new Date());
        order.setUpdateBy("admin");

        //创建支付

        String result = "";

        //支付宝
        if (bo.getPayType() == 2L){
            try {
                result = HfuPayUtils.hFuPayByJs(HfuPayUtils.A_NATIVE, goods.getName(), photo.getPhotoMoney().toString(), order.getOrderNo(), null);

                HfuOrderResultVo resultVo = JsonUtils.parseObject(result, HfuOrderResultVo.class);

                if (resultVo == null || StringUtils.isEmpty(resultVo.getPartyOrderId())){
                    throw new ServiceException("下单失败");
                }

                if (!"10000".equals(resultVo.getBankCode()) || !"00000100".equals(resultVo.getRespCode())){
                    throw new ServiceException("下单失败");
                }
                order.setTradeNo(resultVo.getPartyOrderId());

            } catch (Exception e) {
                throw new ServiceException(e.getMessage());
            }

            log.info("汇付支付宝订单返回：  {}", result);

        }
        //微信
        else if (bo.getPayType() == 3L){
            try {

                if (StringUtils.isEmpty(bo.getOpenId())){
                    throw new ServiceException("openid为空");
                }

                try {
                    result = HfuPayUtils.hFuPayByJs(HfuPayUtils.T_JSAPI, goods.getName(), photo.getPhotoMoney().toString(), order.getOrderNo(), bo.getOpenId());

                    HfuPayResultJsonWxVo jsonWxVo = JsonUtils.parseObject(result, HfuPayResultJsonWxVo.class);

                    if (jsonWxVo == null || !"00000100".equals(jsonWxVo.getRespCode())){
                        throw new ServiceException("下单失败");
                    }

                    order.setTradeNo(jsonWxVo.getPartyOrderId());
                    order.setOpenId(bo.getOpenId());

                }catch (Exception e){
                    throw new ServiceException(e.getMessage());
                }
                log.info("汇付微信订单返回：  {}", result);

            } catch (Exception e) {
                throw new ServiceException(e.getMessage());
            }
        }

        dyOrderMapper.insert(order);

        return result;
    }
}
